package dao

import (
	"context"
	"gorm.io/gorm"
	"jk-time/webook/payment/domain"
	"time"
)

type GormPayment struct {
	db *gorm.DB
}

func NewGormPayment(db *gorm.DB) *GormPayment {
	return &GormPayment{db: db}
}

func (g GormPayment) Insert(ctx context.Context, pmt Payment) error {
	now := time.Now().UnixMilli()
	pmt.Utime = now
	pmt.Ctime = now
	return g.db.WithContext(ctx).Create(&pmt).Error
}

func (g GormPayment) UpdateTxnIDAndStatus(ctx context.Context, bizTradeNo string, txnID string,
	status uint8) error {
	return g.db.WithContext(ctx).Model(&Payment{}).Where("biz_trade_no=?", bizTradeNo).Updates(map[string]any{
		"txn_id": txnID,
		"status": status,
		"utime":  time.Now().UnixMilli(),
	}).Error
}

func (g GormPayment) FindExpiredPayment(ctx context.Context, offset int, limit int, t time.Time) ([]Payment, error) {
	var res []Payment
	err := g.db.WithContext(ctx).Where("status=? and utime<?", uint8(domain.PaymentStatusInit),
		t.UnixMilli()).Offset(offset).Limit(limit).Find(&res).Error
	return res, err
}

func (g GormPayment) GetPayment(ctx context.Context, bizTradeNO string) (Payment, error) {
	var res Payment
	err := g.db.WithContext(ctx).Where("biz_trade_no = ?", bizTradeNO).First(&res).Error
	return res, err
}
